# 商品管理
from django import forms
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.forms.models import model_to_dict
from web.models import Product, Goods_Image, Users, Goods_Category, Goods_Category_Sub
from web.apis import tools
from django.db.models import Q
from pypinyin import lazy_pinyin, Style

# 商品表单
class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = "__all__"

    def clean_name(self):
        name = self.cleaned_data.get('name')
        if not name:
            raise forms.ValidationError("商品名称不能为空")
        if len(name) > 30:
            raise forms.ValidationError("商品名称不能超过30个字符")
        return name

    def clean_price(self):
        price = self.cleaned_data.get('price')
        if price <= 0:
            raise forms.ValidationError("商品价格必须大于0")
        return price

    def clean_stock(self):
        stock = self.cleaned_data.get('stock')
        if stock < 0:
            raise forms.ValidationError("商品库存不能小于0")
        return stock

    def clean_shelf_staff(self):
        shelf_staff = self.cleaned_data.get('shelf_staff')
        if not Users.objects.filter(id=shelf_staff).exists():
            raise forms.ValidationError("商品上架员不存在")
        return shelf_staff

    def clean(self):
        cleaned_data = super().clean()
        category = cleaned_data.get('category')
        category_sub = cleaned_data.get('category_sub')

        # 验证分类选择
        if category and category_sub:
            raise forms.ValidationError("商品不能同时属于主分类和次分类")
        if not category and not category_sub:
            raise forms.ValidationError("商品必须属于一个分类（主分类或次分类）")

        return cleaned_data

# 商品图片表单
class GoodsImageForm(forms.ModelForm):
    class Meta:
        model = Goods_Image
        fields = ['product', 'image']  # 明确指定需要的字段
    
    def clean_product(self):
        product = self.cleaned_data.get('product')
        if isinstance(product, (int, str)):
            try:
                return Product.objects.get(id=product)
            except Product.DoesNotExist:
                raise forms.ValidationError("商品不存在")
        return product

# 创建商品
@csrf_exempt
def create_product(request):
    if request.method == 'POST':
        form = ProductForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                product = form.instance
                product_dict = model_to_dict(product)
                product_dict['create_time'] = product.create_time.strftime('%Y-%m-%d %H:%M:%S')
                product_dict['update_time'] = product.update_time.strftime('%Y-%m-%d %H:%M:%S')
                return JsonResponse(tools.ReturnData(code=200, msg='创建商品成功', data=product_dict))
            except Exception as e:
                return JsonResponse(tools.ReturnData(code=400, msg=f'创建商品失败: {str(e)}'))
        else:
            print(form.errors)
            error_msg = tools.get_first_error(form)
            return JsonResponse(tools.ReturnData(code=400, msg=f' {error_msg}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 获取商品列表
@csrf_exempt
def get_product_list(request):
    if request.method == 'GET':
        try:
            products = Product.objects.all().order_by('create_time')
            product_list = []
            for product in products:
                product_dict = model_to_dict(product)
                product_dict['create_time'] = product.create_time.strftime('%Y-%m-%d %H:%M:%S')
                product_dict['update_time'] = product.update_time.strftime('%Y-%m-%d %H:%M:%S')
                
                # 获取商品图片
                images = Goods_Image.objects.filter(product=product)
                image_list = []
                for image in images:
                    image_dict = {
                        'id': image.id,
                        'product': image.product_id,
                        'image': image.image.url if image.image else None,
                        'create_time': image.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                        'update_time': image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                    }
                    image_list.append(image_dict)
                product_dict['images'] = image_list
                
                # 获取分类名称
                if product.category:
                    product_dict['category_name'] = product.category.name
                if product.category_sub:
                    product_dict['category_sub_name'] = product.category_sub.name
                
                # 获取上架员名称
                if product.shelf_staff:
                    shelf_staff = Users.objects.filter(id=product.shelf_staff).first()
                    if shelf_staff:
                        product_dict['shelf_staff_name'] = shelf_staff.username
                
                product_list.append(product_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='获取商品列表成功', data=product_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取商品列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 获取单个商品
@csrf_exempt
def get_product(request, product_id):
    if request.method == 'GET':
        try:
            product = Product.objects.filter(id=product_id).first()
            if not product:
                return JsonResponse(tools.ReturnData(code=400, msg='商品不存在'))
            
            product_dict = model_to_dict(product)
            product_dict['create_time'] = product.create_time.strftime('%Y-%m-%d %H:%M:%S')
            product_dict['update_time'] = product.update_time.strftime('%Y-%m-%d %H:%M:%S')
            # 获取商品图片
            images = Goods_Image.objects.filter(product=product)
            product_dict['images'] = [{'id': image.id, 'product': image.product_id, 'image': image.image.url if image.image else None, 'create_time': image.create_time.strftime('%Y-%m-%d %H:%M:%S'), 'update_time': image.update_time.strftime('%Y-%m-%d %H:%M:%S')} for image in images]
            return JsonResponse(tools.ReturnData(code=200, msg='获取商品信息成功', data=product_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取商品信息失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))
# 获取单个商品(根据product_id查询   )
@csrf_exempt
def get_product_v2(request):
    if request.method == 'GET':
        product_id = request.GET.get('product_id')
        try:
            product = Product.objects.filter(product_id=product_id).first()
            if not product:
                product = Product.objects.filter(id=product_id).first()
                if not product:
                    return JsonResponse(tools.ReturnData(code=400, msg='商品不存在'))
            
            
            product_dict = model_to_dict(product)
            product_dict['create_time'] = product.create_time.strftime('%Y-%m-%d %H:%M:%S')
            product_dict['update_time'] = product.update_time.strftime('%Y-%m-%d %H:%M:%S')
            # 获取商品图片
            images = Goods_Image.objects.filter(product=product)
            product_dict['images'] = [{'id': image.id, 'product': image.product_id, 'image': image.image.url if image.image else None, 'create_time': image.create_time.strftime('%Y-%m-%d %H:%M:%S'), 'update_time': image.update_time.strftime('%Y-%m-%d %H:%M:%S')} for image in images]
            return JsonResponse(tools.ReturnData(code=200, msg='获取商品信息成功', data=product_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取商品信息失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 更新商品
@csrf_exempt
def update_product(request, product_id):
    if request.method == 'POST':
        try:
            product = Product.objects.filter(id=product_id).first()
            if not product:
                return JsonResponse(tools.ReturnData(code=400, msg='商品不存在'))
            
            form = ProductForm(request.POST, instance=product)
            if form.is_valid():
                form.save()
                product_dict = model_to_dict(form.instance)
                product_dict['create_time'] = form.instance.create_time.strftime('%Y-%m-%d %H:%M:%S')
                product_dict['update_time'] = form.instance.update_time.strftime('%Y-%m-%d %H:%M:%S')
                return JsonResponse(tools.ReturnData(code=200, msg='更新商品成功', data=product_dict))
            else:
                error_msg = tools.get_first_error(form)
                return JsonResponse(tools.ReturnData(code=400, msg=f' {error_msg}'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'更新商品失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用PUT方法'))

# 删除商品
@csrf_exempt
def delete_product(request, product_id):
    if request.method == 'DELETE':
        try:
            product = Product.objects.filter(id=product_id).first()
            if not product:
                return JsonResponse(tools.ReturnData(code=400, msg='商品不存在'))
            
            product.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除商品成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除商品失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))

# 上传商品图片
@csrf_exempt
def upload_product_image(request, product_id):
    if request.method == 'POST':
        try:
            product = Product.objects.filter(id=product_id).first()
            if not product:
                return JsonResponse(tools.ReturnData(code=400, msg='商品不存在'))
            
            if 'image' not in request.FILES:
                return JsonResponse(tools.ReturnData(code=400, msg='请上传图片'))
            
            # 使用product对象初始化表单
            form = GoodsImageForm(
                data={'product': product_id},  # 传入product_id
                files=request.FILES
            )
            
            if form.is_valid():
                form.save()
                image_dict = model_to_dict(form.instance)
                image_dict['image'] = form.instance.image.url
                image_dict['create_time'] = form.instance.create_time.strftime('%Y-%m-%d %H:%M:%S')
                image_dict['update_time'] = form.instance.update_time.strftime('%Y-%m-%d %H:%M:%S')
                return JsonResponse(tools.ReturnData(code=200, msg='上传商品图片成功', data=image_dict))
            else:
                error_msg = tools.get_first_error(form)
                return JsonResponse(tools.ReturnData(code=400, msg=f' {error_msg}'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'上传商品图片失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 删除商品图片
@csrf_exempt
def delete_product_image(request, image_id):
    if request.method == 'DELETE':
        try:
            image = Goods_Image.objects.filter(id=image_id).first()
            if not image:
                return JsonResponse(tools.ReturnData(code=400, msg='商品图片不存在'))
            
            image.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除商品图片成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除商品图片失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))

# 获取商品图片列表
@csrf_exempt
def get_product_images(request, product_id):
    if request.method == 'GET':
        try:
            product = Product.objects.filter(id=product_id).first()
            if not product:
                return JsonResponse(tools.ReturnData(code=400, msg='商品不存在'))
            
            images = Goods_Image.objects.filter(product=product)
            image_list = []
            for image in images:
                image_dict = model_to_dict(image)
                image_dict['image'] = image.image.url
                image_dict['create_time'] = image.create_time.strftime('%Y-%m-%d %H:%M:%S')
                image_dict['update_time'] = image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                image_list.append(image_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='获取商品图片列表成功', data=image_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取商品图片列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 搜索
@csrf_exempt
def search_product(request):
    """
    搜索商品
    参数:
    - name: 商品名称或拼音首字母或商品ID
    返回:
    - 商品列表
    """
    if request.method == 'GET':
        name = request.GET.get('name', '').strip()
        try:
            query = Q()
            if name:
                # 构建搜索条件
                search_conditions = Q()
                
                # 1. 搜索商品名称（中文）- 优先匹配
                search_conditions |= Q(name__icontains=name)
                
                # 2. 搜索商品ID - 精确匹配
                if name.isalnum() or '-' in name or '_' in name:
                    search_conditions |= Q(product_id__icontains=name)
                
                # 3. 搜索拼音（包括全拼和首字母）
                # 将输入转换为小写，以支持大小写不敏感的搜索
                name_lower = name.lower()
                
                # 判断是否为纯拼音输入（不包含中文）
                is_pure_pinyin = all(not ('\u4e00' <= char <= '\u9fff') for char in name)
                if is_pure_pinyin:
                    # 如果是纯拼音输入，使用更严格的匹配
                    search_conditions |= Q(pinyin__startswith=name_lower)
                else:
                    # 如果是中文输入，转换为拼音首字母进行搜索
                    pinyin_initials = ''.join([p[0] for p in lazy_pinyin(name, style=Style.FIRST_LETTER)])
                    if pinyin_initials:
                        # 使用更严格的匹配，确保首字母完全匹配
                        search_conditions |= Q(pinyin__startswith=pinyin_initials.lower())
                
                query &= search_conditions
                
            products = Product.objects.filter(query).order_by('-create_time')
            product_list = []
            for product in products:
                product_dict = model_to_dict(product)
                # 如果该商品的分类是下架，则不显示
                if product.category:
                    if product.category.status != 1:
                        continue
                if product.category_sub:
                    if product.category_sub.status != 1:
                        continue
                product_dict['create_time'] = product.create_time.strftime('%Y-%m-%d %H:%M:%S')
                product_dict['update_time'] = product.update_time.strftime('%Y-%m-%d %H:%M:%S')
                # 获取商品图片
                images = Goods_Image.objects.filter(product=product)
                image_list = []
                for image in images:
                    image_dict = {
                        'id': image.id,
                        'product': image.product_id,
                        'image': image.image.url if image.image else None,
                        'create_time': image.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                        'update_time': image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                    }
                    image_list.append(image_dict)
                product_dict['images'] = image_list
                # 分类、上架员等信息同get_product_list
                if product.category:
                    product_dict['category_name'] = product.category.name
                if product.category_sub:
                    product_dict['category_sub_name'] = product.category_sub.name
                if product.shelf_staff:
                    shelf_staff = Users.objects.filter(id=product.shelf_staff).first()
                    if shelf_staff:
                        product_dict['shelf_staff_name'] = shelf_staff.username
                product_list.append(product_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='搜索商品成功', data=product_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'搜索商品失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 批量更新商品拼音首字母
@csrf_exempt
def update_products_pinyin(request):
    if request.method == 'POST':
        try:
            # 获取所有没有拼音首字母的商品
            products = Product.objects.filter(Q(pinyin__isnull=True) | Q(pinyin=''))
            updated_count = 0
            error_products = []
            
            for product in products:
                try:
                    # 更新拼音首字母
                    product.pinyin = ''.join([p[0] for p in lazy_pinyin(product.name, style=Style.FIRST_LETTER)])
                    product.save()
                    updated_count += 1
                except Exception as e:
                    error_products.append({
                        'id': product.id,
                        'name': product.name,
                        'error': str(e)
                    })
            
            return JsonResponse(tools.ReturnData(
                code=200, 
                msg=f'更新完成，成功更新{updated_count}个商品，失败{len(error_products)}个商品',
                data={
                    'updated_count': updated_count,
                    'error_products': error_products
                }
            ))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'更新商品拼音首字母失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

